package com.hbisdt.cet.sample.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

/**
 *
 * @author : 教学案例
 * @version : 1.0
 * @date : 2025-05-08 15:52
 */
@Service
public class CarbonCollectService {

    /**
     * 异步收集碳数据
     * 该方法使用了@Async注解，表明它将在一个单独的线程中异步执行
     * 这样做是为了避免阻塞主线程，从而提高应用程序的响应速度和效率
     * @throws InterruptedException 如果线程被中断，将会抛出此异常
     */
    @Async
    public void collect() throws InterruptedException {
        System.out.println("碳排放数据收集 开始...");
        Long startTime = System.currentTimeMillis();
        Thread.sleep(5000);
        Long entTime = System.currentTimeMillis();
        System.out.println("碳排放数据收集 结束...");
        System.out.println("碳排放数据收集 耗时：" + (entTime - startTime));
    }

    @Async
    public Future<Integer> processA() throws InterruptedException {
        System.out.println("开始进行碳排放数据 统计...");
        Long startTime = System.currentTimeMillis();
        Thread.sleep(5000);
        int result = 111111;
        Long endTime = System.currentTimeMillis();
        System.out.println("碳排放数据 统计耗时：" + (endTime - startTime));
        return new AsyncResult<Integer>(result);
    }

    @Async
    public Future<Integer> processB() throws InterruptedException {
        System.out.println("开始进行碳排放数据 计算分析...");
        Long startTime = System.currentTimeMillis();
        Thread.sleep(6000);
        int result = 222222;
        Long endTime = System.currentTimeMillis();
        System.out.println("碳排放数据 计算分析耗时：" + (endTime - startTime));
        return new AsyncResult<Integer>(result);
    }
}
